package com.leyou.auth.contrller;

import com.leyou.auth.config.JwtProperties;
import com.leyou.auth.entity.UserInfo;
import com.leyou.auth.service.AuthService;
import com.leyou.auth.utils.JwtUtils;
import com.leyou.common.enums.ExceptionEnums;
import com.leyou.common.exception.LyException;
import com.leyou.common.utils.CookieUtils;
import com.netflix.client.http.HttpResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.http.HttpRequest;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Controller
public class AuthController {
    @Autowired
    private AuthService authService;
    @Autowired
    private JwtProperties jwtProperties;

    //用户登陆,生成jwt放进cookie返回客户端
    @PostMapping("login")
    public ResponseEntity<Void> login(@RequestParam("username") String username,
                                      @RequestParam("password") String password,
                                      HttpServletRequest request,
                                      HttpServletResponse response) {

        //调用service生成jwt
        String token = authService.login(username, password);
        //设置cookie
        CookieUtils.setCookie(request,
                response,
                jwtProperties.getCookieName(),
                token,
                60 * jwtProperties.getExpire());

        return ResponseEntity.ok().build();
    }

    //根据jwt获取用户信息，返回给前端,并且刷新过期时间
    @GetMapping("verify")
    public ResponseEntity<UserInfo> verify(@CookieValue("LY_TOKEN") String token,
                                           HttpServletRequest request, HttpServletResponse response) {
        UserInfo userInfo = authService.verify(token);

        //生成jwt，过期时间就刷新了
        try {
            String jwt = JwtUtils.generateToken(userInfo,
                    jwtProperties.getPrivateKey(),
                    jwtProperties.getExpire());
        } catch (Exception e) {
            throw new LyException(ExceptionEnums.LOGIN_ERROR);
        }
        //重新设置cookie，过期时间也刷新了
        CookieUtils.setCookie(request,
                response,
                jwtProperties.getCookieName(),
                token,
                60 * jwtProperties.getExpire());

        return ResponseEntity.ok(userInfo);
    }


}
